#!/usr/bin/env python3
import os
import cv2
from camera.imx219_cam import Imx219Camera

os.environ["DISPLAY"] = ":0"

def main():
    
    cam = Imx219Camera("/dev/video22", name="IMX219")

    if not cam.open_v4l2():
        print("[ERROR] 摄像头打开失败")
        return

    cv2.namedWindow("IMX219")
    cv2.moveWindow("IMX219", 0, 0)
    
    print("[INFO] 开始采集，按 'q' 退出或 Ctrl+C 停止")

    try:
        while True:
            frame = cam.read()

            if frame is None:
                continue
            
            # 可在此添加图像处理代码
            # start_point = (0, 0)
            # end_point = (200, 100)
            # color = (0, 255, 0)
            # thickness = 2
            # cv2.rectangle(frame, start_point, end_point, color, thickness)

            cv2.imshow("IMX219", frame)

            key = cv2.waitKey(1) & 0xFF
            if key == ord('q'):
                print("[INFO] 用户按下 'q'，停止采集")
                break
            
    except KeyboardInterrupt:
        print("\n[INFO] 用户中断，停止采集")
    except Exception as e:
        print(f"[ERROR] 发生错误: {e}")
    finally:
        cam.release()
        cv2.destroyAllWindows()

if __name__ == "__main__":
    main()